<template>
  <b-page class="channel-manage ">
    <div class="table-page-search-wrapper">
      <a-row :gutter="48">
        <a-col :md="20" :sm="24">
          <b-button
            type="primary"
            btnContent="新增渠道码"
            @click="addModel">
          </b-button>
          <span class="qrCode-tips">*由于微信公众号二维码机制原因，每个渠道二维码下载后有效期为30天，请及时更新</span>
        </a-col>
        <a-col :md="4">
          <div style="display: flex;justify-content: flex-end;align-items: center">
            <a-button type="link">查看使用教程</a-button>
          </div>
        </a-col>
      </a-row>

    </div>
    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :pageSize="10"
    >
      <span slot="qrCode" slot-scope="text, record">
        <img style="width: 40px;height:40px;" @click="previewImg(record.id)" src="@/perm/assets/qrCodeDefault.png">
      </span>
      <span slot="expireTime">
        永久有效
      </span>
      <span slot="createTime" slot-scope="text, record">
        {{ getTime(record.createTime) }}
      </span>

      <span slot="operation" slot-scope="text, record">
        <a-button type="link" @click="downloadQrCode(record)">下载</a-button>
        <a-button type="link" @click="gotoData(record.gameTaskId)">数据</a-button>
        <a-button type="link" @click="editModel(record)">编辑</a-button>
        <a-button type="link" @click="deleteModel(record.id)">删除</a-button>
      </span>
    </s-table>

    <a-modal
      v-model="showChannel"
      :title="null"
      width="640px"
      @ok="saveChannel"
      @cancel="showChannel=false">
      <div class="modal-class-title">
        {{ editChannel.id?'编辑':'新建' }}渠道码
      </div>
      <div class="modal-class-content d-aic">
        <div class="channel-name-label">渠道名称：</div>
        <a-input v-model="editChannel.name"/>
      </div>
      <div class="modal-class-content d-aic">
        <div class="channel-name-label">裂变成员：</div>
        <a-select
          placeholder="裂变成员"
          style="width: 200px;height: 32px"
          @change="memberChange">
          <a-select-option v-for="(item,index) in memberList" :key="index">
            <img class="member-list-avatar" :src="item.avatar"><span class="member-list-name">{{ item.name }}</span>
          </a-select-option>
        </a-select>
      </div>
    </a-modal>
    <a-modal
      v-model="showQrCode"
      title="截图保存渠道二维码"
      width="640px"
      centered
      @cancel="showQrCode=false">
      <div class="d-fdc-aic">
        <img :src="qrCode">
        <div>
          {{ selectedChannel }}
        </div>
      </div>

    </a-modal>
    <x-qr-code
      ref="qrCode"
      @openQrCode="openQrCode"
      :style="{
        maxWidth: '300px',
        maxHeight: '300px',
      }"/>
  </b-page>
</template>

<script>
    import { STable } from '@/components'
    import BButton from '../../../components/b-button'
    import API from '../../../../api/channel'
    import XQrCode from '../../../components/XQrCode'
    import COMMON_API from '../../../../api/common'

    export default {
        name: 'ChannelManage',
        components: {
            XQrCode,
            BButton,
            STable
        },
        data () {
            return {
                qrCode: null,
                showQrCode: false,
                editChannel: { name: null },
                showChannel: false,
                selectedChannel: '',
                // 表头
                columns: [
                    {
                        title: '编号',
                        dataIndex: 'id',
                        align: 'center',
                        width: '80px'
                    },
                    {
                        title: '渠道名称',
                        dataIndex: 'name',
                        align: 'center',
                        width: '80px'
                    },
                    {
                        title: '二维码',
                        align: 'center',
                        width: '100px',
                        scopedSlots: { customRender: 'qrCode' }
                    },
                    {
                        title: '有效期',
                        align: 'center',
                        width: '100px',
                        scopedSlots: { customRender: 'expireTime' }
                    },
                    {
                        title: '创建时间',
                        align: 'center',
                        width: '90px',
                        dataIndex: 'createTime',
                        scopedSlots: { customRender: 'createTime' }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        width: '200px',
                        dataIndex: 'operation',
                        scopedSlots: { customRender: 'operation' }
                    }
                ],
                // 加载数据方法 必须为 Promise 对象
                loadData: parameter => {
                    const params = {
                        qwUserId: this.$store.state.user.info.qwUserId || null,
                        gameTaskId: this.$route.query.gameTaskId || null
                    }
                    return API.ChannelPage(Object.assign({
                        current: parameter.pageNo,
                        size: parameter.pageSize
                    }, params))
                        .then(res => {
                            return {
                                data: res.records,
                                'pageSize': res.size,
                                'pageNo': res.current,
                                'totalCount': res.total
                            }
                        })
                },
                selectedRowKeys: [],
                selectedRows: [],
                // custom table alert & rowSelection
                options: {},
                memberList: []
            }
        },
        created () {
            this.options = {
                alert: {
                    show: true,
                    clear: () => {
                        this.selectedRowKeys = []
                    }
                },
                rowSelection: {
                    selectedRowKeys: this.selectedRowKeys,
                    onChange: this.onSelectChange
                }
            }
        },
        computed: {
            qwUserId () {
                return this.$store.state.user.info.qwUserId
            },
            gameTaskId () {
                return this.$route.query.gameTaskId
            }
        },
        mounted () {
            this.initActive()
        },
        methods: {
            initActive () {
                COMMON_API.listGameActive({ qwUserId: this.qwUserId, gameTaskId: this.gameTaskId }).then(res => {
                    this.memberList = res
                })
            },
            memberChange (data) {
                this.editChannel.gameMemberUserId = this.memberList[data].userId
            },
            getTime (time) {
                return this.$Utils.getTimeFormat(time).substring(0, 16)
            },
            previewImg (channelId) {
            },
            addModel () {
                this.editChannel = Object.assign({}, { name: null })
                this.showChannel = true
            },
            editModel (channel) {
                this.editChannel = Object.assign({}, channel)
                this.showChannel = true
            },
            downloadQrCode (channel) {
                API.createQrCode({
                    qwUserId: this.qwUserId,
                    channelId: channel.id,
                    gameTaskId: this.gameTaskId
                }).then(res => {
                    this.showQrCode = true
                    this.qrCode = res.src
                    // this.$refs.qrCode.generate(res)
                    this.selectedChannel = channel.name
                }).catch(() => {
                })
            },
            openQrCode (image) {
                this.showQrCode = true
                this.qrCode = image
            },
            gotoData (gameTaskId) {
                this.$router.push({
                    path: '/qywx/sjfx/page',
                    query: {
                        gameTaskId: gameTaskId,
                        active: '3'
                    }
                })
            },
            deleteModel (channelId) {
                const self = this
                this.$warning({
                    title: `确认删除吗？`,
                    okText: '确认',
                    okType: 'primary',
                    maskClosable: true,
                    onOk () {
                        API.deleteChannel({ qwUserId: self.qwUserId, channelId: channelId }).then(() => {
                            self.$message.success(`删除成功`)
                            self.$refs.table.refresh(true)
                        }).catch(() => {
                            self.$message.error(`删除失败，请稍后再试`)
                        })
                    }
                })
            },
            saveChannel () {
                if (!this.editChannel.name || !this.editChannel.name.trim()) {
                    this.$message.warning(`请填写渠道名称`)
                    return
                }
                if (!this.editChannel.gameMemberUserId) {
                    this.$message.warning(`请选择裂变成员`)
                    return
                }
                this.editChannel.qwUserId = this.qwUserId
                this.editChannel.gameTaskId = this.gameTaskId
                API.saveChannel(this.editChannel).then(() => {
                    this.$message.success(`保存成功`)
                    this.showChannel = false
                    this.editChannel = Object.assign({}, {})
                    this.$refs.table.refresh(true)
                }).catch(() => {
                    this.$message.error(`保存错误，请稍后再试`)
                })
            },
            onSelectChange (selectedRowKeys, selectedRows) {
                this.selectedRowKeys = selectedRowKeys
                this.selectedRows = selectedRows
            }
        }
    }
</script>

<style scoped lang="less">
    .modal-class-title {
        padding-bottom: 22px;
        font-size: 20px;
        color: #262626;
    }

    .modal-class-content {
        margin: 20px 0;
    }

    .channel-name-label {
        flex-shrink: 0;
        margin-right: 10px;
        font-size: 14px;
        color: #595959;
    }

    .channel-manage {
        .table-page-search-wrapper {
            padding-bottom: 20px;
        }

        .qrCode-tips {
            margin-left: 17px;
            font-size: 14px;
            color: #595959;
        }

    }

</style>
